package com.hk.kindheartedness;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.model.User;
import com.hk.kindheartedness.util.DateUtil;
import com.hk.kindheartedness.util.RegexUtil;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.Date;
import java.util.Objects;

/**
 * 更新采购员信息
 */
public class BuyerUpdateActivity extends AppCompatActivity implements View.OnClickListener {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

//  Initialize button
    private Button updateBuyerBtn;

    private EditText userName,phone,idNumber,age,address;

    private TextView userId;

    private RadioButton man,woman;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyer_update);
//        实例化
        dbOpenHelper = new DBOpenHelper(BuyerUpdateActivity.this, "db_kindheartedness", null, 1);
//        获取采购员信息控制权
        userId = findViewById(R.id.userId);
        userName = findViewById(R.id.userName);
        phone = findViewById(R.id.phone);
        idNumber = findViewById(R.id.idNumber);
        age = findViewById(R.id.age);
        address = findViewById(R.id.address);
//         获取性别控制权
        man = findViewById(R.id.man);
        woman = findViewById(R.id.woman);
//        获取更新按钮控制权
        updateBuyerBtn = findViewById(R.id.updateBuyerBtn);
        updateBuyerBtn.setOnClickListener(this);
//        提取回显的采购员详情
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
//        回显获取的采购员数据
        echoBuyer(bundle);

    }

    /**
     * 获取采购员详情数据
     * @param bundle
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void echoBuyer(Bundle bundle) {
        if (Objects.isNull(bundle)) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"获取对象信息失败,请重试！");
            return;
        }
        String buyerToString = (String) bundle.get("buyer");
        if (Objects.nonNull(buyerToString)) {
            User user = JSON.parseObject(buyerToString, User.class);
//                进行回显
            userId.setText(user.getId().toString());
            userName.setText(user.getUserName());
            phone.setText(user.getPhone());
            idNumber.setText(user.getIdNumber());
            age.setText(user.getAge().toString());
//                进行性别判断
            if (user.getSex() == 0) {
                man.setChecked(true);
            } else {
                woman.setChecked(true);
            }
            address.setText(user.getAddress());
            return;
        }
        toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"获取对象信息失败,请重试！");
        return;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            更新采购员信息
            case R.id.updateBuyerBtn:
                updateBuyerInfo();
                break;
            default:
        }
    }

    /**
     * 更新采购员信息
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("LongLogTag")
    private void updateBuyerInfo() {
        String buyerId = userId.getText().toString();
        String buyerUserName = userName.getText().toString();
        String buyerPhone = phone.getText().toString();
        String buyerIdNumber = idNumber.getText().toString();
        String buyerAge = age.getText().toString();
//        判断选择的性别
        String buyerSex = "0";
        if (woman.isChecked()) {
            buyerSex = "1";
        }
        String buyerAddress = address.getText().toString();
        Boolean check = checkBuyerData(buyerId,buyerUserName,buyerPhone,buyerIdNumber,buyerAge,buyerSex,buyerAddress);
        if (check) {
            SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        查询ID对应的采购员信息
            Cursor cursor = readableDatabase.query("user", null, "id = ?", new String[]{buyerId}, null, null, null);
            User user = null;
            while (cursor.moveToNext()) {
                Integer id = null,sex = null,age = null;
                try {
                    id = Integer.valueOf(cursor.getString(0));
                    sex = Integer.valueOf(cursor.getString(6));
                    age = Integer.valueOf(cursor.getString(7));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    Log.e("BuyerUpdateActivity.java","数据转化数字失败，请检查数据！");
                }
                String userName = cursor.getString(1);
                String phone = cursor.getString(2);
                String idNumber = cursor.getString(8);
                String address = cursor.getString(9);
                user = new User();
                user.setId(id);user.setUserName(userName);
                user.setPhone(phone);user.setSex(sex);
                user.setAge(age);user.setIdNumber(idNumber);
                user.setAddress(address);
            }
            if (user == null) {
                toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"未查到此数据,请刷新重试！");
                return;
            }
//                    封装需要更新的采购员信息
            ContentValues contentValues = new ContentValues();
            contentValues.put("username",buyerUserName);
            contentValues.put("phone",buyerPhone);
            contentValues.put("id_number",buyerIdNumber);
            contentValues.put("age",buyerAge);
            contentValues.put("sex",buyerSex);
            contentValues.put("address",buyerAddress);
            contentValues.put("update_time", DateUtil.dateString(new Date()));
//                    执行更新采购员信息
            int update = readableDatabase.update("user", contentValues, "id = ?", new String[]{buyerId});
            if (update == 1) {
                toast = ToastUtil.toastHint(toast, BuyerUpdateActivity.this, "采购员更新成功，请返回进行查看！");
                return;
            }
            toast = ToastUtil.toastHint(toast, BuyerUpdateActivity.this, "采购员更新失败，请稍后重试！");
            return;

        }
    }

    /**
     * 校验采购员信息
     * @param buyerId 采购员编号
     * @param buyerUserName 名称
     * @param buyerPhone 手机号
     * @param buyerIdNumber 身份证号码
     * @param buyerAge 年龄
     * @param buyerSex 性别
     * @param buyerAddress 地址
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private Boolean checkBuyerData(String buyerId, String buyerUserName, String buyerPhone, String buyerIdNumber, String buyerAge, String buyerSex, String buyerAddress) {
        //        校验图书编号
        if (buyerId.equals("") || buyerId.equals(null) || buyerId == null) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"采购员编号不能为空！");
            return false;
        }
        if (!RegexUtil.checkChinese(buyerUserName)) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"采购员姓名只支持中文！");
            return false;
        }
        if (!RegexUtil.checkMobile(buyerPhone)) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"请输入正确的手机号！");
            return false;
        }
        if (!RegexUtil.checkIdCard(buyerIdNumber)) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"请输入正确的身份证号！");
            return false;
        }
        if (!RegexUtil.checkDigitz(buyerAge)) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"请输入正确的年龄！");
            return false;
        }
        if (!buyerSex.equals("0") && !buyerSex.equals("1")) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"请选择性别！");
            return false;
        }
        if (buyerAddress.equals("")) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"请输入地址！");
            return false;
        }

        //        校验信息是否存在
//        打开数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        校验手机号是否已被注册
        String buyerId2 = null;
        Cursor query = readableDatabase.query("user", null, "phone = ?", new String[]{buyerPhone}, null, null, null);
        while (query.moveToNext()) {
            buyerId2 = query.getString(0);
        }
//        如果存在值，表示已经被注册
        if (Objects.nonNull(buyerId)) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"该手机号已被注册！");
            return false;
        }
        //        校验身份证号是否已被注册
        String buyerId3 = null;
        Cursor query2 = readableDatabase.query("user", null, "id_number = ?", new String[]{buyerIdNumber}, null, null, null);
        while (query2.moveToNext()) {
            buyerId3 = query2.getString(0);
        }
//        如果存在值，表示已经被注册
        if (Objects.nonNull(buyerId2)) {
            toast = ToastUtil.toastHint(toast,BuyerUpdateActivity.this,"该身份证号已被注册！");
            return false;
        }
        return true;
    }

    /**
     * 重写onKeyDown()方法来拦截用户单击后退按钮事件
     * @param keyCode 按键标识
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        判断按下的是否为后退按键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            返回上一页标识是否刷新
//            setResult(RESULT_OK,new Intent());
            startActivityForResult(new Intent(BuyerUpdateActivity.this,BuyerAdminActivity.class),RESULT_OK);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}